const iconv = require("iconv-lite");
const axios = require('axios')
const cheerio = require('cheerio');
const fetch = require('node-fetch')


// const username = '201941417440'
// const password = 'Zhz84300754'
// const start_year = '2021'
// const end_year = '2022'
// const tearm = '0'

function gettoken() {
    return new Promise((resolve, reject) => {
        let url = 'https://cas.dgut.edu.cn/home/Oauth/getToken/appid/jwyd.html?%3Akey=%3Avalue'
        let header = {
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
            'Accept-Encoding': 'gzip, deflate, br',
            'Accept-Language': 'zh-CN,zh;q=0.9',
            'Cache-Control': 'max-age=0',
            'Connection': 'keep-alive',
            'Host': 'cas.dgut.edu.cn',
            'Referer': 'http://jwyd.dgut.edu.cn/',
            'sec-ch-ua': '" Not A;Brand";v="99", "Chromium";v="96", "Google Chrome";v="96"',
            'sec-ch-ua-mobile': '?0',
            'sec-ch-ua-platform': '"Windows"',
            'Sec-Fetch-Dest': 'document',
            'Sec-Fetch-Mode': 'navigate',
            'Sec-Fetch-Site': 'cross-site',
            'Sec-Fetch-User': '?1',
            'Upgrade-Insecure-Requests': '1',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36',
        }
        fetch(url, {
            method: "get",
            headers: header
        }).then(res => {
            // 获取 cookie
            const cookie = res.headers.get('set-cookie')
            // 清理一下 cookie 的格式，移除过期时间，只保留基础的键值对才能正常使用
            const real_cookie = cookie
                .replace(/expires=(.+?);\s/gi, '')
                .replace(/path=\/(,?)(\s?)/gi, '')
                .trim()
            return {
                text: res.text(),
                cookie: real_cookie
            };
        }).then(async data => {
            let patt = /var token = "(.+?)";/
            let token = patt.exec(await data.text)[1]
            console.log("token=" + token);
            resolve({
                token: token,
                cookie: data.cookie
            })
        })
    })
}


function gettoken2(username, password) {
    return new Promise(async (resolve, reject) => {
        let token_cookie = await gettoken()
        let token = token_cookie.token
        let cookie = token_cookie.cookie
        let url = 'https://cas.dgut.edu.cn/home/Oauth/getToken/appid/jwyd.html'
        let headers = {
            'Accept': 'application/json, text/javascript, */*; q=0.01',
            'Accept-Encoding': 'gzip, deflate, br',
            'Accept-Language': 'zh-CN,zh;q=0.9',
            'Connection': 'keep-alive',
            'Content-Length': '100',
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
            'Host': 'cas.dgut.edu.cn',
            'Origin': 'https://cas.dgut.edu.cn',
            'Referer': 'https://cas.dgut.edu.cn/home/Oauth/getToken/appid/jwyd.html',
            'sec-ch-ua': '" Not A;Brand";v="99", "Chromium";v="96", "Google Chrome";v="96"',
            'sec-ch-ua-mobile': '?0',
            'sec-ch-ua-platform': '"Windows"',
            'Sec-Fetch-Dest': 'empty',
            'Sec-Fetch-Mode': 'cors',
            'Sec-Fetch-Site': 'same-origin',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36',
            'X-Requested-With': 'XMLHttpRequest',
            cookie: cookie
        }
        data = `username=${username}&password=${password}&__token__=${token}&wechat_verify=`
        // console.log(data);
        fetch(url, {
            method: 'POST',
            headers: headers,
            body: data,
            mode: "cors",
            credentials: 'include'
        }).then(res => {
            return res.json()
        }).then(res => {
            let resjson = JSON.parse(res)
            if (resjson.code === 1) {
                let patt = /token=(.+?)$/
                let token2 = patt.exec(resjson.info)[1];
                console.log("token2" + token2);
                resolve(
                    token2
                )
            } else reject('账号或密码错误')
        }).catch(function (error) {
            console.log('request failed', error)
        })
    }).catch((e) => {})

}
// gettoken2('201941417440', 'Zhz84300754').then(res => {
//     console.log(res);
// })
function get_JSESSIONID(username, password) {
    return new Promise(async (resolve, reject) => {
        const token2 = await gettoken2(username, password)
        const url = `http://jwyd.dgut.edu.cn/login?token=${token2}`
        const headers = {
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
            'Accept-Encoding': 'gzip, deflate',
            'Accept-Language': 'zh-CN,zh;q=0.9',
            'Connection': 'keep-alive',
            'Host': 'jwyd.dgut.edu.cn',
            'Upgrade-Insecure-Requests': '1',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36',
        }
        fetch(url, {
            method: 'get',
            header: headers,
            redirect: 'manual' // 手动重定向
        }).then(res => {
            const pattern = /JSESSIONID=(.+?);/
            let JSESSIONID = pattern.exec(res.headers.get('set-cookie'))[1]
            resolve(JSESSIONID)
        }).catch(error => {
            console.log(error);
        })
    }).catch((e) => {})
}

function getMark(username, password, year_start, year_end, xq) {
    return new Promise(async (resolve, reject) => {
        const JSESSIONID = await get_JSESSIONID(username, password)
        console.log('JSESSIONID=' + JSESSIONID);
        const url = 'http://jwyd.dgut.edu.cn/student/xscj.stuckcj_data.jsp'
        const headers = {
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
            'Accept-Encoding': 'gzip, deflate',
            'Accept-Language': 'zh-CN,zh;q=0.9',
            'Cache-Control': 'max-age=0',
            'Connection': 'keep-alive',
            'Content-Length': '102',
            'Content-Type': 'application/x-www-form-urlencoded',
            'Host': 'jwyd.dgut.edu.cn',
            'Cookie': `JSESSIONID=${JSESSIONID}`,
            'Origin': 'http://jwyd.dgut.edu.cn',
            'Referer': 'http://jwyd.dgut.edu.cn/student/xscj.stuckcj.jsp?menucode=b',
            'Upgrade-Insecure-Requests': '1',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36',
        }
        let data = `sjxz=sjxz3&ysyx=yscj&zx=1&fx=1&xn=${year_start}&xn1=${year_end}&xq=${xq}&ysyxS=on&sjxzS=on&zxC=on&fxC=on&menucode_current=`
        axios({
            method: 'post',
            url: url,
            data: data,
            headers: headers,
            responseType: "arraybuffer"
        }).then(function (response) {
            let html = iconv.decode(response.data, "gbk");
            resolve(html)
        })
    }).catch((e) => {})
}

async function analysisHTML(username, password, start_year, end_year, tearm) {
    const html = await getMark(username, password, start_year, end_year, tearm)
    const $ = cheerio.load(html);
    ls = []
    $('tbody tr').map(function (index, element) {
        let text = $(this).text()
        text = text.replace(/[\r\t]/g, ''); // 去除特殊字符
        text = text.replace(/[\n]/g, '#') // 分隔开课程与成绩
        ls.push(text);
    })
    const mark = []
    ls.map((val, index) => {
        pp = val.split('#')
        if (index === 0) {
            mark.push(pp[1])
        } else {
            let class_name = pp[2] // 科目
            let jidian = pp[3] // 绩点
            let chengji = pp[9] // 成绩
            mark.push({
                class_name: class_name,
                jidian: jidian,
                chengji: chengji
            })
        }
    })
    return new Promise((resolve, reject) => {
        if (mark.length !== 0) {
            resolve(mark)
        } else reject('解析HTML出错')
    }).catch((e) => {})
}
exports.markk = async (req, res) => {
    const body = req.body
    const html = await analysisHTML(body.username, body.password, body.start_year, body.end_year, body.tearm)
    if (typeof html == "undefined") {
        res.send({
            code: 400,
            msg: '账号或密码错误！'
        })
        return
    }
    res.send({
        code: 200,
        mark: html
    })
}